package com.rjwh.dingdong.client.activity.community;

import android.Manifest;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.design.widget.AppBarLayout;
import android.support.v7.widget.Toolbar;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.aishua.lib.utils.AsAppUtils;
import com.aishua.lib.utils.AsStrUtils;
import com.rjwh.dingdong.client.R;
import com.rjwh.dingdong.client.activity.BaseActivity;
import com.rjwh.dingdong.client.activity.image.ImageListBrowseActivity;
import com.rjwh.dingdong.client.activity.image.PhotoListActivity;
import com.rjwh.dingdong.client.application.MyApplication;
import com.rjwh.dingdong.client.bean.localbean.ModularTab;
import com.rjwh.dingdong.client.bean.localbean.TagFilter;
import com.rjwh.dingdong.client.bean.localbean.TopicData;
import com.rjwh.dingdong.client.constant.LocalConstant;
import com.rjwh.dingdong.client.mvp.presenter.impl.CommunityPostPublishPresenter;
import com.rjwh.dingdong.client.mvp.view.CommunityPostPublishView;
import com.rjwh.dingdong.client.util.FileUtils;
import com.rjwh.dingdong.client.util.LogUtil;
import com.rjwh.dingdong.client.util.Photo;
import com.rjwh.dingdong.client.util.TheradPoolUtil;
import com.rjwh.dingdong.client.util.UploadUtil;
import com.rjwh.dingdong.client.view.PhotoDialog;
import com.rjwh.dingdong.client.view.PublishTopicParagraphLayout;
import com.rjwh.dingdong.client.view.PublishTopicParagraphLayout.onParagraphListener;
import com.rjwh.dingdong.client.view.PublishTopicTagView;
import com.rjwh.dingdong.client.view.PublishTopicTagView.OnFlowTagViewListener;
import com.rjwh.dingdong.client.widget.FaceRootView.onFaceViewListener;
import com.tbruyelle.rxpermissions.RxPermissions;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import rx.functions.Action1;

/**
 * 社区--发帖
 *
 * @author 王小珂
 * @ClassName CommunityPostPublishActivity
 * @Description TODO(这里用一句话描述这个类的作用)
 * @date 2016-4-18 上午9:23:01
 * @history 1.YYYY-MM-DD author: description:
 */
public class CommunityPostPublishActivity extends BaseActivity implements OnClickListener, onParagraphListener, onFaceViewListener, OnFlowTagViewListener, CommunityPostPublishView {
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.app_bar_layout)
    AppBarLayout appBarLayout;
    @BindView(R.id.community_post_publish_paragaraph_ll)
    LinearLayout paragaraphLayout;// 段落主宿主
    @BindView(R.id.community_post_publish_sv)
    ScrollView scrollView;
    @BindView(R.id.community_post_publish_bottom_root_add_paragraph)
    TextView addParagraphView;
    //    @BindView(R.id.act_community_post_publish_bottom_root_face_icon)
//    ImageView faceIV;
    @BindView(R.id.community_post_publish_bottom_root_send_btn)
    Button sendBtn;
    @BindView(R.id.community_post_publish_center_tv)
    TextView textCenterTV;
    @BindView(R.id.community_post_publish_center_ll)
    LinearLayout titleCenterLl;
    @BindView(R.id.community_post_publish_title_et)
    EditText titleEt;
    //    @BindView(R.id.act_community_post_publish_face_send_root_view)
//    FaceRootView faceRootView;
    private AlertDialog tagSelectDialog;
    // 标签宿主
    private LinearLayout tagview_root_ll;
    // 当前默认的段落的View
    private PublishTopicParagraphLayout currentParagaraphView;
    // tagView的集合
    private List<PublishTopicTagView> tagLayouts = new ArrayList<>();
    // 存放段落
    private List<PublishTopicParagraphLayout> listParagaraphView = new ArrayList<>();

    private PhotoDialog photoDialog;

    private int imageCount;
    private String currentModularId;
    //存储拍照返回的图片路径
    private String cutImgPath;

    private String attachids = "";
    private String subids = "";
    private String modularname;
    private String replyid;
    private String parentid;
    private String topicid;
    private boolean isReply;
    private static final String REGEX = "^,*|,*$";
    private static final int PICTAKEPHOTO = 1;
    private static final int IMAGELISTBROWSE = 3;
    private static final int MAXPHOTOCOUNT = 9;
    private List<ModularTab> modularlist;
    private List<TagFilter> tagFilters;

    private CommunityPostPublishPresenter presenter;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.community_post_publish);
        ButterKnife.bind(this);
        parseIntent();
        initView();
        presenter = new CommunityPostPublishPresenter(this, this);
    }


    @SuppressWarnings("unchecked")
    private void parseIntent() {
        Intent intent = getIntent();
        if (intent != null) {
            isReply = intent.getBooleanExtra("isReply", false);
            currentModularId = intent.getStringExtra("modularid");
            modularname = intent.getStringExtra("modularname");
            modularlist = (List<ModularTab>) intent.getSerializableExtra("modularlist");
            tagFilters = (List<TagFilter>) intent.getSerializableExtra("modularfilters");
            topicid = intent.getStringExtra("topicid");
            replyid = intent.getStringExtra("replyid");
            parentid = intent.getStringExtra("parentid");
        }
        LogUtil.d("CommunityPostPublishActivity", "currentModularId: " + currentModularId + ";topicid: " + topicid + ";parentid: " + parentid + ";replyid: " + replyid);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // requestCode = 5 , resultCode = 8
        // 选择相册
        if (requestCode == LocalConstant.SELECT_REQUEST_MOOD_PICS && resultCode == RESULT_OK) {
            if (data != null) {
                final List<String> temList = data.getStringArrayListExtra("list");
                if (temList != null && !temList.isEmpty()) {
                    if (currentParagaraphView != null) {
                        currentParagaraphView.addImageList(temList);
                    }
                }
            }
        }
        switch (requestCode) {
            case PICTAKEPHOTO:// 拍照
                if (resultCode == RESULT_OK) {
                    if (AsAppUtils.hasSdcard() && !AsStrUtils.isEmpty(cutImgPath)) {
                        File tempFile = new File(cutImgPath);
                        if (!tempFile.exists()) {
                            showToast("图片不存在！");
                            return;
                        }
                        String newPicPath = tempFile.getAbsolutePath();
                        List<String> picNameList = new ArrayList<>();
                        picNameList.add(newPicPath);
                        currentParagaraphView.addImageList(picNameList);
                    } else {
                        showToast("未找到存储卡，无法存储照片！");
                    }
                }
                break;
            case IMAGELISTBROWSE:// 浏览删除
                if (data != null) {
                    ArrayList<String> pathList = data.getStringArrayListExtra("pathList");
                    if (currentParagaraphView != null) {
                        currentParagaraphView.delImageList(pathList);
                    }
                }
                break;

            default:
                break;
        }

    }

    private void initView() {
        initToolbarHelper(isReply);
        if (isReply) {
            titleEt.setVisibility(View.GONE);
            titleCenterLl.setVisibility(View.GONE);
        } else {
            titleEt.setVisibility(View.VISIBLE);
            titleCenterLl.setVisibility(View.VISIBLE);
        }
        titleCenterLl.setOnClickListener(this);
        if (!AsStrUtils.isEmpty(modularname)) {
            textCenterTV.setText(modularname.trim());
        }
        // 默认显示一个段落
        addParagraph();
        assert addParagraphView != null;
        addParagraphView.setOnClickListener(this);
        assert sendBtn != null;
        sendBtn.setOnClickListener(this);

        photoDialog = new PhotoDialog(this);
        photoDialog.setBackLsn(new PhotoDialog.onBackLsn() {
            @Override
            public void onClick(int type) {
                if (type == 0) {
                    PhotoListActivity.startActivityForResult(CommunityPostPublishActivity.this,
                            LocalConstant.SELECT_REQUEST_MOOD_PICS, MAXPHOTOCOUNT - imageCount);
                } else {
                    RxPermissions.getInstance(getBaseContext())
                            .request(Manifest.permission.CAMERA)
                            .subscribe(new Action1<Boolean>() {
                                @Override
                                public void call(Boolean aBoolean) {
                                    if (aBoolean) {
                                        cutImgPath = FileUtils.getTempImageStorageDirectory() + System.currentTimeMillis() + ".png";
                                        Photo.startComer(CommunityPostPublishActivity.this, PICTAKEPHOTO, Uri.fromFile(new File(cutImgPath)));
                                    }
                                }
                            }, new Action1<Throwable>() {
                                @Override
                                public void call(Throwable throwable) {
                                    LogUtil.d("CommunityPostPublishActivity", "observable error: " + throwable.getMessage());
                                }
                            });
                }
            }
        });
    }

    /**
     * init the toolbar
     *
     * @param isReply
     */
    protected void initToolbarHelper(boolean isReply) {
        this.setSupportActionBar(this.toolbar);
        if (isReply) {
            getSupportActionBar().setTitle("回帖");
        } else {
            getSupportActionBar().setTitle("");
        }
        getSupportActionBar().setHomeButtonEnabled(true); //设置返回键可用
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowHomeEnabled(true);
    }

    /**
     * 点击发送
     */
    public void sendPosts() {
        /* 如果是发帖就对标题判断非空,回帖则没有标题 */
        if (!isReply) {
            // 标题为空时光标跳转到标题输入栏
            if (AsStrUtils.isEmpty(titleEt.getText().toString())) {
                showToast("请输入标题");
                return;
            }
        }
        /* 判断内容非空 */
        if (listParagaraphView != null && !listParagaraphView.isEmpty()) {
            for (PublishTopicParagraphLayout paragraph : listParagaraphView) {
                if (AsStrUtils.isEmpty(paragraph.getText()) && paragraph.getImageList().isEmpty()) {
                    showToast("请输入内容");
                    return;
                }
            }
        } else {
            showToast("请添加内容");
            return;
        }

        /* 如果是发帖则需选择标签,回帖直接发送 */
        if (!isReply) {
            showTagSelectDialog();
        } else {
            showLoadDialog();
            TheradPoolUtil.getInstant().getExecutor().execute(new Runnable() {

                @Override
                public void run() {
                    Message msg = new Message();
                    msg.obj = getContent();
                    callBackHandler.sendMessage(msg);
                }
            });
        }
    }


    Handler callBackHandler = new Handler() {

        public void handleMessage(Message msg) {
            String address = MyApplication.spUtil.getStrPreferenceByParamName(CommunityPostPublishActivity.this, LocalConstant.SP_LOC_PROVINCE) + MyApplication.spUtil.getStrPreferenceByParamName(CommunityPostPublishActivity.this, LocalConstant.SP_LOC_CITY);
            if (isReply) {
                presenter.doPublishReply("", topicid, parentid, replyid, "", msg.obj.toString(), attachids, address);
            } else {
                presenter.doPublishTopic(currentModularId, titleEt.getText().toString(), msg.obj.toString(), attachids, subids, address);
            }
        }
    };

    /**
     * 获取待发送的内容,包括文字和图片
     */
    public String getContent() {
        final StringBuilder messageSb = new StringBuilder();
        final StringBuilder aidSb = new StringBuilder();

        if (listParagaraphView != null && !listParagaraphView.isEmpty()) {
            for (int i = 0; i < listParagaraphView.size(); i++) {
                PublishTopicParagraphLayout paragraph = listParagaraphView.get(i);
                String text = paragraph.getText();
                messageSb.append(text);
                List<String> pictureList = paragraph.getImageList();
                for (int j = 0, k = pictureList.size(); j < k; j++) {
                    final String picPath = pictureList.get(j);
                    if (!AsStrUtils.isEmpty(picPath)) {
                        String aid;
                        if (isReply) {
                            aid = UploadUtil.uploadPic(picPath, "");
                        } else {
                            aid = UploadUtil.uploadPic(picPath, currentModularId);
                        }
                        if (!AsStrUtils.isEmpty(aid)) {
                            aidSb.append(aid);
                            if (j + 1 < k) {
                                aidSb.append(",");
                            }
                            messageSb.append("[attachimg]").append(aid).append("[/attachimg]");
                        }
                    }
                }
                // 多段落时分割加","
                if (i + 1 < listParagaraphView.size()) {
                    aidSb.append(",");
                }
                if (i + 1 < listParagaraphView.size()) {
                    messageSb.append("\r\n");
                }
            }
        }
        attachids = aidSb.toString().replaceAll(REGEX, "");
        return messageSb.toString();
    }

    /**
     * 添加标签
     */
    private void addTagView(TagFilter tagFilter) {
        PublishTopicTagView publishTopicTagView = new PublishTopicTagView(this);
        publishTopicTagView.setOnTopicTagViewListener(this);
        publishTopicTagView.setTagData(tagFilter);
        tagview_root_ll.addView(publishTopicTagView);
        tagLayouts.add(publishTopicTagView);
    }

    /**
     * 发帖选择标签对话框
     */
    protected void showTagSelectDialog() {
        tagSelectDialog = new AlertDialog.Builder(this).create();
        tagSelectDialog.show();
        Window window = tagSelectDialog.getWindow();
        window.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        window.setContentView(R.layout.dialog_tag_select);
        window.setGravity(Gravity.CENTER);
        tagview_root_ll = (LinearLayout) window.findViewById(R.id.my_dialog_tag_select_tagview_root_ll);
        Button dialogOk = (Button) window.findViewById(R.id.my_dialog_tag_select_send_btn);
        for (int i = 0; i < tagFilters.size(); i++) {
            LogUtil.e("CommunityPostPublishActivity", "tagFilters: " + tagFilters.get(i).getItems().size());
            addTagView(tagFilters.get(i));
        }
        dialogOk.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                tagSelectDialog.dismiss();
                tagview_root_ll.removeAllViews();
                tagLayouts.clear();
                showLoadDialog();
                TheradPoolUtil.getInstant().getExecutor().execute(new Runnable() {

                    @Override
                    public void run() {
                        Message msg = new Message();
                        msg.obj = getContent();
                        callBackHandler.sendMessage(msg);
                    }
                });
            }

        });
    }

    /**
     * 添加段落
     */
    private void addParagraph() {
        PublishTopicParagraphLayout itemParagraphLayout = new PublishTopicParagraphLayout(CommunityPostPublishActivity.this);
        itemParagraphLayout.setonParagraphListener(CommunityPostPublishActivity.this);
        listParagaraphView.add(itemParagraphLayout);
        paragaraphLayout.addView(itemParagraphLayout);
    }

    private Runnable runnable = new Runnable() {
        public void run() {
            scrollView.fullScroll(ScrollView.FOCUS_DOWN);
        }
    };

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.community_post_publish_bottom_root_add_paragraph:
                addParagraph();// 添加段落
                scrollView.post(runnable);
                hideSoftInputView();
                break;
            case R.id.community_post_publish_bottom_root_send_btn:
                sendPosts();
                break;
            case R.id.community_post_publish_center_ll:
                showBottomListDialog();
                break;
            default:
                break;
        }
    }

    private void showBottomListDialog() {
        String[] names = new String[0];
        if (modularlist != null && !modularlist.isEmpty()) {
            names = new String[modularlist.size()];
            for (int i = 0; i < modularlist.size(); i++) {
                names[i] = modularlist.get(i).getName().trim();
            }
        }
        if (names.length > 0) {
            new android.support.v7.app.AlertDialog.Builder(this)
                    .setItems(names, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                            textCenterTV.setText(modularlist.get(which).getName().trim());
                            currentModularId = modularlist.get(which).getId();
                        }
                    })
                    .show();
        } else {
            new android.support.v7.app.AlertDialog.Builder(this).setMessage("加载失败").show();
        }
    }

    @Override
    public void delItemView(PublishTopicParagraphLayout view) {
        paragaraphLayout.removeView(view);
        listParagaraphView.remove(view);
    }

    @Override
    public void addImage(PublishTopicParagraphLayout view) {
        this.currentParagaraphView = view;
        imageCount = 0;
        imageCount += view.getImageListCount();
        if (imageCount >= MAXPHOTOCOUNT) {
            showToast("上传最多不超过9张！");
            return;
        }
        photoDialog.show();
    }

    @Override
    public void editInput(PublishTopicParagraphLayout view) {
        this.currentParagaraphView = view;
    }

    @Override
    public void showImage(PublishTopicParagraphLayout view, int position) {
        this.currentParagaraphView = view;
        List<String> pathlist = view.getImageList();
        ArrayList<String> list = new ArrayList<>();
        list.addAll(pathlist);
        Intent intent = new Intent(this, ImageListBrowseActivity.class);
        Bundle bundle = new Bundle();
        bundle.putSerializable("pathlist", list);
        intent.putExtras(bundle);
        intent.putExtra("position", position);
        startActivityForResult(intent, IMAGELISTBROWSE);
    }

    @Override
    public void showFaceView(String key) {
        for (int j = 0; j < listParagaraphView.size(); j++) {
            PublishTopicParagraphLayout publishPostLinearLayout = listParagaraphView.get(j);
            publishPostLinearLayout.setEditText(key);
        }
    }

    @Override
    public void setTagCheck(PublishTopicTagView view) {
        // 获取点击时的subid
        final StringBuilder subidSb = new StringBuilder();
        for (int i = 0, j = tagLayouts.size(); i < j; i++) {
            PublishTopicTagView tagLayout = tagLayouts.get(i);
            String subid = tagLayout.getSubid();
            LogUtil.d("CommunityPostPublishActivity", "subid:" + subid);
            if (!AsStrUtils.isEmpty(subid)) {
                subidSb.append(subid);
                if (i + 1 < j) {
                    subidSb.append(",");
                }
            }
        }
        subids = subidSb.toString().replaceAll(REGEX, "");
    }

    @Override
    public void showLoading() {
        showLoadDialog();
    }

    @Override
    public void dismissLoading() {
        dismissLoadDialog();
    }

    @Override
    public void LoadTopicData(TopicData topicData) {
        if (topicData != null) {
            Intent intent = new Intent(CommunityPostPublishActivity.this, CommunityPostDetailActivity.class);
            String url = topicData.getFilepath() + "?userid=" + MyApplication.spUtil.getStrPreferenceByParamName(MyApplication.app, LocalConstant.SP_USERID) + "&platform=ANDROID" + "&version=" + MyApplication.versionCode + "&udid=" + MyApplication.deviceId + "&babyid=" + MyApplication.spUtil.getStrPreferenceByParamName(MyApplication.app, LocalConstant.SP_BABYID) + "&token=" + MyApplication.spUtil.getStrPreferenceByParamName(MyApplication.app, LocalConstant.SP_USER_TOKEN);
            intent.putExtra("url", url);
            intent.putExtra("topicid", topicData.getTopicid());
            startActivity(intent);
        }
        this.finish();
    }

    @Override
    public void LoadReplyData(String resultMsg) {
        if (!AsStrUtils.isEmpty(resultMsg)) {
            Intent data = new Intent();
            data.putExtra("postid", resultMsg);
            setResult(RESULT_OK, data);
        }
        this.finish();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        presenter.detachView();
        scrollView.removeCallbacks(runnable);
        callBackHandler.removeCallbacksAndMessages(null);
    }
}
